import random
import time

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway, Counter
import pandas as pd
from bqtool.utils.tools import get_db

i = 0
alarm = 0


def push_gateway(data_count,alarm_count):
    # registry = CollectorRegistry()
    # g_c = Gauge('gps_data_count', 'gps数据', ['instance', 'type'], registry=registry)
    # g_c.labels(instance='host66', type='gpst').set(data_count)
    # push_to_gateway('10.2.111.51:9092', job='pct', registry=registry)
    alarm_reg = CollectorRegistry()
    alarm_g = Gauge('data_count', '当天业务数据总数', ['instance', 'type'], registry=alarm_reg)
    # alarm_gt = Gauge('data_count_t', '当天业务数据总数t', ['instance', 'type'], registry=alarm_reg)
    # alarm_gt.labels(instance='host66', type='gpst').set(data_count)
    alarm_g.labels(instance='host66', type='gps').set(data_count)
    alarm_g.labels(instance='host66', type='alarm').set(alarm_count)
    push_to_gateway('10.2.111.51:9092', job='pc',registry=alarm_reg)
    print('发送成功')


def read_count(client):
    c = pd.read_sql_query("""
    select count(0) from  T_GPS_RECORDINFO_TEST t 
    """, client)
    print('ok')
    return c.iloc[0][0]


def read_data(client):
    c = pd.read_sql_query("""
    select t.id,t.deviceid,t.gpstime,t.longtitude,t.latitude,t.devicetype from T_GPS_RECORDINFO_201901 t where t.gpstime between 
    to_date('2019/1/23 10:00:00','yyyy/MM/dd HH24:mi:ss') and to_date('2019/1/23 11:00:00','yyyy/MM/dd HH24:mi:ss')
    """, client)
    print('ok')
    return c


def insert(data, client):
    global i
    add = i + random.randint(1, 10)
    data = data.iloc[i:add]
    i = add
    data.save('t_gps_recordinfo_test', client)
    print('保存成功')


def in_alarm(data, client):
    global alarm
    add = alarm + random.randint(5, 15)
    data = data.iloc[alarm:add]
    alarm = add
    data.save('t_event_alarm', client)
    print('保存警情成功')

def read_alarm(client):
    df = pd.read_sql("""
    select * from T_EVENT_ALARM """, client)
    return df

if __name__ == '__main__':
    client = get_db('ehl_public', 'ehl1234', '10.2.111.66')
    alarmSourceClient = get_db('ehl_application', 'ehl1234', '10.2.15.16')
    alarmClient = get_db('ehl_application', 'ehl1234', '10.2.111.66')
    c = read_data(client)
    alarmData = read_alarm(alarmSourceClient)
    while (True):
        insert(c, client)
        count = read_count(client)
        in_alarm(alarmData, alarmClient)
        alarm_count = len(read_alarm(alarmClient))
        push_gateway(count,alarm_count)
        time.sleep(30)
